﻿var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var schedule = require("node-schedule");
var signCode = "slel3@lsl334xx,deka";
var Cio = require('socket.io-client');
var log = require("./../util/loginfo").getInstand;
var redis_dao = require("./dao/redis_dao");
var gameInfo = require('./class/game').getInstand;
var gameConfig = require('./config/gameConfig');

var Csocket = Cio('http://localhost:13000');

Csocket.on('disconnect', function (data) {
	log.info("登录服务器被断开")
});

Csocket.on('connected', function (msg) {
	log.info("与登录服务器进行连接......");
	var info = { serverName: "百人场_1014_Color", serverId: gameConfig.serverId, signCode: "slel3@lsl334xx,deka" };
	Csocket.emit('GameServerConnect', info)
})

Csocket.on('GameServerConnectResult', function (msg) {
	if (msg.resultCode) {
		log.info("连接成功");
	}
})


Csocket.on('LoginGameResult', function (msg) {
	if (!msg) {
		return;
	}
	log.info(".登录百人场_1014_ColorGame服务器回应" + msg)
	if (msg.ResultCode) {
		gameInfo.updateUser(msg.userInfo);
	} else {
		gameInfo.deleteUserById(msg.userid, msg.msg);
	}

})

Csocket.on('addgold', function (msg) {
	if (!msg) {
		return;
	}
	//log.info(msg);
	var result = gameInfo.addgold(msg.userid, msg.addgold);
	Csocket.emit('addgoldResult', { Result: result });

	//当前用户桌子广播
	var User = gameInfo.getUser(msg.userid);
	if (User) {
		var tablestring = "table" + User.getTable();
		io.sockets.in(tablestring).emit('userGoldUpdate', { userId: msg.userid, updateSocre: User.getScore() });
	}
})

Csocket.on('getgold', function (msg) {
	if (!msg) {
		return;
	}

	//log.info(msg);
	var score = gameInfo.getPlayerScore(msg.userid);
	Csocket.emit('getgoldResult', { Result: 1, score: score });

})

Csocket.on('disconnectUser', function (msg) {
	//log.info("disconnectUser" + msg.userId);
	var list = gameInfo.getOnlinePlayer();
	if (list[msg.userId]) {
		// kicked, ZZZ-20230509
		list[msg.userId]._socket.emit(msg.sysCommand, msg);
		list[msg.userId]._socket.disconnect();
	} else {
		log.info("用户不存在");
		var result = { ResultCode: 0, userId: msg.userId };
		Csocket.emit("userDisconnect", result);
	}
})


Csocket.on('applyMatchResult', function (_info) {
	//log.info(_info);
	gameInfo.addRankUserList(_info);
	//gameInfo.fishShoot(socket,fishShootInfo);
})


Csocket.on('Setmaintain', function () {
	gameInfo.Setmaintain();
})


gameInfo.setIo(io, Csocket);

io.on('connection', function (socket) {

	//log.info(socket + 'connected');
	socket.emit('connected', 'connect game server');


	//客户登录游戏
	socket.on('LoginGame', function (GameInfo) {
		try {
			var data = JSON.parse(GameInfo);
			GameInfo = data;
		} catch (e) {
			log.warn('LoginGame-json');
		}

		//是不是维护模式
		if (gameInfo.isMaintain()) {
			log.info("维护模式,禁止登录!");
			socket.emit("maintain", { ResultCode: 1, msg: true });
			return;
		}

		//log.info("test1.进入房间")
		//log.info(GameInfo)
		if (!GameInfo) {
			log.info("登录游戏,参数不正确!");
			return;
		}

		if (GameInfo.sign) {

			if (!gameInfo.getUser(GameInfo.userid)) {
				gameInfo.addUser(GameInfo, socket);
				var msg = {
					userid: GameInfo.userid,
					sign: GameInfo.sign,
					gameId: gameInfo.serverId,
					serverSign: signCode,
					serverId: gameConfig.serverId
				};
				Csocket.emit('LoginGame', msg);
				//log.info("test4.发送新用户登录完成,让登录服务器删除用户")
			} else {
				log.info("用户已经在服务器了，无需重复登录");
			}
		}

	});

	//然后再登录房间
	socket.on('LoginRoom', function (RoomInfo) {
		try {
			var data = JSON.parse(RoomInfo);
			RoomInfo = data;
		} catch (e) {
			log.warn('LoginRoom-json');
		}
		//如果没有房间概念，就默认为1
		//这还应该检测是否进入了游戏，如果没有需要先进入
		//log.info("进入房间")
		gameInfo.LoginRoom(socket.userId, RoomInfo.roomid, socket)
	});


	//离开房间
	socket.on('LogoutRoom', function () {
		gameInfo.LogoutRoom(socket);
	});


	//登录游戏获取免费游戏次数
	socket.on('LoginfreeCount', function () {
		gameInfo.LoginfreeCount(socket.userId, socket);
	});


	//下注
	socket.on('lottery', function (lottery) {
		log.info("下注");
		try {
			var data = JSON.parse(lottery);
			lottery = data;
		} catch (e) {
			//log.warn('lottery-json');
		}

		var result = gameInfo.lottery(socket.userId, lottery);
		if (result.code < 1) {
			socket.emit('lotteryResult', { ResultCode: result.code });
		} else {
			io.sockets.emit('lotteryResult', { ResultCode: result.code, bet_dict: result.bet_dict })
		}

	});

	//获取游戏状态
	socket.on('getGameType', function () {
		log.info("获取游戏状态");
		redis_dao.get_bet_list().then(res => {
			var redis_dict = res;
			socket.emit('getGameTypeResult', {
				game_type: gameInfo.game_type,
				bet_time: gameConfig.GAME_BET_TIME,
				open_time: gameConfig.GAME_END_TIME,
				times: gameInfo.remaintimes,
				bet_type: gameConfig.coinConfig,
				bet_list: redis_dict
			});

		}).catch(e => {

		})

	});


	//获取排行榜和神算子
	socket.on('getGameRankingList', function (lottery) {
		log.info("获取排行榜和神算子");
		socket.emit('getGameRankingListResult', {
			ranking_list: gameInfo.bet_pai_hang_list,
			shen_suan_zi: gameInfo.shen_suan_zi,
		});

	});

	//获取历史游戏记录
	socket.on('getGameRecordList', function (lottery) {
		log.info("获取历史记录")
		socket.emit('getGameRecordListResult', {
			game_record_list: gameInfo.game_record_list,
		});

	});


	//离线操作
	socket.on('disconnect', function () {
		if (!socket.userId) {
			return;
		}
		//通知登录服务器，已经下线存储游戏数据
		//log.info(socket.userId)
		var userInfo = gameInfo.getUser(socket.userId);
		if (userInfo) {
			if (userInfo.Islogin()) {
				gameInfo.deleteUser(socket);
				var result = {
					ResultCode: 1,
					userId: userInfo._userId,
					userScore: userInfo._score,
					gameId: gameConfig.serverId,
					nolog: true
				};
				Csocket.emit("userDisconnect", result);
				//断线存储相应数据(在新的数据库里存储,消耗子弹与收获金币)
				socket.userId = null;
			} else {
				userInfo._isLeave = true;
				log.warn('未更新用户数据离开');
			}
		} else {
			log.info("用户未登录离开!")
		}
	})


});


app.set('port', process.env.PORT || gameConfig.port);

var server = http.listen(app.get('port'), function () {
	log.info('start at port:' + server.address().port);
});


log.info("百人场_1014_Color服务器启动");

